package com.spring.sso.config.security.authentication;

import com.alibaba.fastjson.JSON;
import com.spring.sso.common.CommonResult;
import com.spring.sso.config.AuthenticationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : pangfuzhong
 * @description
 * @date : 2021/9/16 16:28
 */
@Slf4j
public class VerificationAuthenticationFailEntryPoint implements AuthenticationEntryPoint, AccessDeniedHandler {

    public VerificationAuthenticationFailEntryPoint() {
    }

    /**
     * 未登录或token认证失败
     * */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("--> 用户未登录或token认证失败");
    }

    /**
     * 无权访问, 有无权限访问接口由后端进行控制，当账号成功认证后，返回对应的角色以及角色下可访问的菜单权限，按钮权限给前端，此时也就不会存在没有权限访问的情况
     * */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(CommonResult.failed(4001,"暂无权限！")));
    }
}
